<script setup>
import api from '../api/ticketApi.js'
import { ref, onMounted, computed } from "vue"
import lodash from "lodash";
import UserApi from "@/api/userApi.js";
import ticketApi from "../api/ticketApi.js";
import { useRouter } from 'vue-router'

// 获取路由对象
const router = useRouter();
//定义绑定的数据
//表格中的数据
const total=ref(0);
const tableData = ref({});
const orderBuy=ref( false);
//查询数据
const searchObj = ref({
  current: 1,
  limit: 10,
  total: 0,
  count: 0,
  fromStationName: '',
  toStationName: '',
  departDate: '2025-08-15'
});

//要修改或者新增的数据
const obj = ref({});

// 页面加载后使用默认查询条件查询数据
onMounted(async () => {
  await searchTickets();
})

// 查询车票的方法
const searchTickets = async () => {
  // 验证日期必填字段
  if (!searchObj.value.departDate) {
    alert('请选择出发日期');
    return;
  }
  try {
    console.log('查询车票shijianshijian:', searchObj.value)
    tableData.value = await api.page(searchObj.value);
    total.value = tableData.value.count;
  } catch (error) {
    console.error('查询车票失败:', error);
    alert('查询失败，请重试');
  }
}

// 判断是否有数据
const hasData = computed(() => {
  return tableData.value &&
      tableData.value.data &&
      Array.isArray(tableData.value.data) &&
      tableData.value.data.length > 0;
})

//订票
const handlebuy = async (index, row) => {
  obj.value = lodash.clone(row);
  const user = await UserApi.getByToken();
  obj.value.id=user.id;
  obj.value.realName=user.realName;
  obj.value.idCard=user.idCard;
  if (obj.value.remainSeats <= 0) {
    alert('该车次已无票');
  } else if (obj.value.status != 1) {
    alert('该车次已停运');
  } else if (obj.value.remainSeats > 0 && obj.value.status == 1) {
    orderBuy.value = true;
  }
}

// 关闭订票表单
const closeOrderForm = () => {
  obj.value = {};
  orderBuy.value = false;
}
// 提交订单
const submitOrder = () => {
  // 这里添加提交订单的逻辑
  // 构造符合后端 OrderDetail 类的参数对象
  const orderData = {
    userId: obj.value.id,              // 用户ID
    realName: obj.value.realName,      // 真实姓名
    idCard: obj.value.idCard,          // 身份证号
    trainNode: obj.value.trainNode,    // 列车编号
    trainType: obj.value.trainType,    // 列车类型
    departTime: obj.value.departTime,  // 出发时间
    arriveTime: obj.value.arriveTime,  // 到达时间
    totalAmount: obj.value.price,
    fromStationName: obj.value.fromStationName,
    toStationName: obj.value.toStationName,
    scheduleId: obj.value.scheduleId,
  };
  console.log('提交订单:', orderData);
  ticketApi.submit(orderData);
  // 提交后关闭表单
  orderBuy.value = false;
  alert('订单提交成功，订单有效期为15分钟，请尽快支付')
  router.push('/uncommit')

}

//前一页
const handleSizeChange=() => {
  searchTickets();
}
//后一页
const handleCurrentChange=(val) => {
  searchTickets();
}







</script>

<template>
  <!-- 查询表单 -->
  <el-card class="search-card">
    <el-form :inline="true" :model="searchObj" label-width="80px">
      <el-form-item label="出发站">
        <el-input v-model="searchObj.fromStationName" placeholder="请输入出发站"/>
      </el-form-item>
      <el-form-item label="到达站">
        <el-input v-model="searchObj.toStationName" placeholder="请输入到达站"/>
      </el-form-item>
      <el-form-item label="出发日期">
        <el-date-picker
            v-model="searchObj.departDate"
            type="date"
            placeholder="请选择出发日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchTickets">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 数据展示区域 -->
  <div v-if="hasData" class="table-container">
    <!-- 车票表格 -->
    <el-table :data="tableData.data" style="width: 100%; margin-top: 20px;">
      <el-table-column label="列车编号" prop="trainNode"/>
      <el-table-column label="列车类型" prop="trainType"/>
      <el-table-column label="起始站" prop="fromStationName"/>
      <el-table-column label="终点站" prop="toStationName"/>
      <el-table-column label="发车时间" prop="departTime"/>
      <el-table-column label="到达时间" prop="arriveTime"/>
      <el-table-column label="状态">
        <template #default="scope">
          {{ scope.row.status == 1 ? '正常运行' : '停运' }}
        </template>
      </el-table-column>
  <!--      <el-table-column label="剩余票数" prop="remainSeats"/>-->
      <el-table-column label="票价(元)" prop="price"/>
      <el-table-column align="right">
        <template #default="scope">


          <el-button
              size="small"
              type="primary"
              @click="handlebuy(scope.$index, scope.row)"
          >
            订票
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 无数据提示 -->
  <div v-else class="no-data-container">
    <el-image src="src/img/11.jpg"></el-image>
    <p class="no-data-text">您所查询的时间不在列车计划表中</p>
  </div>

  <!--订票//提交订单//-->
  <!-- 订票对话框 -->
  <el-dialog v-model="orderBuy" title="提交订单" width="600">
    <el-form :model="obj" label-width="100px">
      <el-form-item label="列车编号">
        <el-input v-model="obj.trainNode" disabled />
      </el-form-item>

      <!-- 起始站和终点站放在一行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="起始站">
            <el-input v-model="obj.fromStationName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="终点站">
            <el-input v-model="obj.toStationName" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 发车时间和到达时间放在一行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="发车时间">
            <el-input v-model="obj.departTime" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="到达时间">
            <el-input v-model="obj.arriveTime" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="票价(元)">
        <el-input v-model="obj.price" disabled />
      </el-form-item>
      <el-form-item label="乘客姓名">
        <el-input v-model="obj.realName" disabled />
      </el-form-item>
      <el-form-item label="身份证号">
        <el-input v-model="obj.idCard" disabled />
      </el-form-item>
    </el-form>
<h4>提交订单表示已阅读同意《国铁集团铁路旅客运输规程》《服务条款》</h4>
<h4>订单提交后请在15分钟内支付成功，否则订单将取消</h4>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeOrderForm">取消</el-button>
        <el-button type="primary" @click="submitOrder">提交订单</el-button>
      </div>
    </template>
  </el-dialog>



  <!--分页-->
  <el-pagination
      v-model:current-page="searchObj.current"
      v-model:page-size="searchObj.limit"
      :page-sizes="[10, 20, 30, 40]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />





</template>










<style scoped>
.search-card {
  margin-bottom: 20px;
}

.no-data-container {
  text-align: center;
  padding: 40px 20px;
}

.no-data-image {
  width: 100px;
  height: 100px;
  margin-bottom: 20px;
}

.no-data-text {
  font-size: 16px;
  color: #909399;
  margin: 0;
}
</style>
